package http_orm

import (
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"sync"
)

// 单例模式
var (
	orm  *gorm_orm
	once sync.Once
)

type gorm_orm struct {
	db *gorm.DB
}

func (orm *gorm_orm) DB() *gorm.DB {
	return orm.db
}

func open(driver, dsn string) *gorm.DB {
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	}
	return db
}

func NewGormORM(driver, dsn string) *gorm_orm {
	once.Do(func() { // 使用once.Do()可以保证orm全局只被创建一次
		db := open(driver, dsn)
		orm = &gorm_orm{
			db: db,
		}
	})
	return orm
}
